/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pkg.multipart;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import org.apache.commons.fileupload.FileItem;

public class MemoryFileItem implements FileItem {

    private byte[] buffer;
    private ByteArrayOutputStream baos;
    private String contentType;
    private String name;
    private String fieldName;
    private boolean formField;

    public InputStream getInputStream() throws IOException {

        return new ByteArrayInputStream(get());
    }

    public String getContentType() {
        return contentType;
    }

    public String getName() {
        return name;
    }

    public boolean isInMemory() {
        return true;
    }

    public long getSize() {
        if (baos != null) {
            return baos.size();
        } else if (buffer != null) {
            return buffer.length;
        } else {
            return 0;
        }
    }

    public byte[] get() {
        if (baos != null) {
            buffer = baos.toByteArray();
            baos = null;
        }
        return buffer;
    }

    public String getString(String string) throws UnsupportedEncodingException {
        byte[] buf = get();
        String result = null;
        if (buf != null) {
            result = new String(buf, Charset.forName(string));
        }
        return result;
    }

    public String getString() {

        byte[] buf = get();
        String result = null;
        if (buf != null) {
            result = new String(buf);
        }
        return result;
    }

    public void write(File file) throws Exception {
    }

    public void delete() {
    }

    public String getFieldName() {
        return fieldName;
    }

    public void setFieldName(String string) {
        this.fieldName = string;
    }

    public boolean isFormField() {
        return formField;
    }

    public void setFormField(boolean bln) {
        formField = bln;
    }

    public OutputStream getOutputStream() throws IOException {
        buffer = null;
        baos = new ByteArrayOutputStream();
        return baos;
    }

    public byte[] getBuffer() {
        return buffer;
    }

    public void setBuffer(byte[] buffer) {
        this.buffer = buffer;
    }

    public void setContentType(String contentType) {
        this.contentType = contentType;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String toString() {
        return "MFI name = " + fieldName + " - " + name + " - " + contentType + " " + buffer + " " + baos;
    }
}
